package com.tinem.platform.web.auth.config.handler;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.tinem.platform.module.pojo.co.GatewayHeadName;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author fzh
 * @version v1
 * @program: platform-maven-archetype
 * @className JsonAuthenticationFailureHandler
 * @description TODO
 * @site https://fengzhihao.xyz/
 * @company
 * @create 2021-01-10 14:21
 */
@Service
public class JsonAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler{

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        //判断是否为ajax请求，默认不是
        if(StrUtil.isBlank(request.getParameter("ajax"))){
            response.sendRedirect("/login.do?message="+ URLEncoder.encode(exception.getMessage(),"UTF-8"));
            logger.error("login error:{}",exception);
            return;
        }
        response.setHeader(GatewayHeadName.X_PLATFORM_RES_CODE,"99999999");
        response.setHeader(GatewayHeadName.X_PLATFORM_RES_MESSAGE, Base64.encode(StrUtil.format("{}:{}",exception.getClass().getName(),exception.getMessage())));
    }

}
